/*!
 * touch2move v1.0
 * http://www.asdfz.cn/touch2move/
 *
 *
 * Released under the MIT license
 *
 * Weibo	: @GanisEnder_林皓轩
 * blog		: http://blog.csdn.net/wnow20
 * github	: https://github.com/wnow20
 * oschina  : https://git.oschina.net/wnow20
 *
 */
;(function($) {
	"use strict"

	// params
	var options = {
		overflow: true			//是否溢出显示
	};
	
	// utilities
	var _this = null;
	var active = false;
	var initX, initY,			// 元素原始坐标
		targetX, targetY,		// 元素当前坐标
		startX, startY,			// 鼠标开始坐标
		currX, currY;			// 鼠标当前坐标
	
	// check browser capabilities
	var browser = {
		addEventListener: !!window.addEventListener,
		touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
		transitions: (function(temp) {
		var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
		for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
			return false;
		})(document.createElement('div'))
	};
	$.fn.touch2move = function(params) {
		if(!browser.touch) return false;
		_this = this;
		$.extend(options, params);
		this.bind({
			touchstart	: touchStart,
			touchmove	: touchMove,
			touchend	: touchEnd
		});
	}
	function touchStart(evt) {
		event.preventDefault();
		if (!(initX && initY)) {
			initX = evt.originalEvent.touches[0].clientX;
			initY = evt.originalEvent.touches[0].clientY;
			
			currX = _this.position().left;
			currY = _this.position().top;
		}
		active = true;
	}
	function touchMove(evt) {
		evt.preventDefault();
		if(!active) { return false;}
		var touch = evt.originalEvent.touches[0];
		var x = touch.clientX - initX + currX;
		var y = touch.clientY - initY + currY;
		
		var leaveWidth = $(window).width() - _this.width();
		var leaveHeight = $(window).height() - _this.height()
		if (x < 0) {
			targetX = 0;
		} else if (x > leaveWidth) {
			targetX = leaveWidth;
		} else {
			targetX = undefined;
		}
		if (y < 0) {
			targetY = 0;
		} else if (y > leaveHeight) {
			targetY = leaveHeight;
		} else {
			targetY = undefined;
		}
		
		if (!options.overflow) {
			x = targetX;
			y = targetY;
		}
		_this.css({
			left	: x,
			top		: y
		});
	}
	function touchEnd(evt) {
		event.preventDefault();

		active = false;
		
		process();
	}
	
	// 最后一步加工
	function process() {
		if (options.overflow) {
			_this.animate({
				left	: targetX,
				top		: targetY
			}, 300);
		}
	}
})(window.jQuery || window.Zepto);
